package online.keepon.document.exception;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import online.keepon.document.common.ErrorInfo;
import online.keepon.document.common.Result;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.crypto.BadPaddingException;
import java.nio.file.AccessDeniedException;

/**
 * @author top
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<?> exceptionHandler(Exception e) {


        if (e instanceof TokenExpiredException) {
            log.error("token已过期:{}", e.getMessage());
            return Result.ok(ErrorInfo.VERIFY_FAILED.code(), "token校验不通过(已过期)", null);
        }
        if (e instanceof JWTDecodeException) {
            log.error("token已过期:{}", e.getMessage(), e);
            return Result.ok(ErrorInfo.UNAUTHENTICATION.code(), "token校验异常", null);
        }
        if (e instanceof AccessDeniedException) {
            log.error("token已过期:{}", e.getMessage(), e);
            return Result.ok(ErrorInfo.UNAUTHENTICATION.code(), "token校验异常", null);
        }

        if (e instanceof PlatformException) {
            log.error("该角色已绑定:{}", e.getMessage(), e);
            return Result.ok(ErrorInfo.FAIL.code(), e.getMessage(), null);
        }
        if (e instanceof MaxUploadSizeExceededException) {
            return Result.fail("上传文件不能大于1M");
        }
        if (e instanceof FileSizeLimitExceededException) {
            return Result.fail("上传文件不能大于1M");
        }
        log.info("出现异常:【{}】, 错误位置: {}", e.getMessage(), e);
        return Result.ok(ErrorInfo.EXCEPTION);
    }
}
